import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,StatusBar,
  TouchableOpacity,Modal,TextInput,WebView
} from 'react-native';
import Orientation from 'react-native-orientation';
//import { WebView } from 'react-native-webview';
import BackButton from '../../component/BackButton';
import SoundPlayer from 'react-native-sound-player';
import { TipModal } from '../../component/Tips';
import MyButton from '../../component/MyButton';
import Loading from '../../component/Loading';
import {BASEURL} from '../../api/api';
let {height, width} = Dimensions.get('window');
//var height=640,width=320;
//var js = require('./开场A1_Canvas.js')
//const URL = "http://10.18.32.120:8086";
//const URL = "http://192.168.31.65:8089";
let HTML_URL = BASEURL+'temp/lensHtml?width='+height+'&height='+width+'&lensId=';
var count = 0;
var index = 0;
// let  setWH = `(
// 	function() {
// 		document.getElementById("animation_container").style.width=${width}"px";
// 		document.getElementById("animation_container").style.height=${height}"px";

//  })();`;
export default class TempEdit extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      // title:'预览',
      // headerRight:(<View></View>),
      // headerLeft:<BackButton navigation = {navigation}/>
      header:null,
    }
  };
  constructor(props){
		super(props);
		//alert(width+","+height)
    this.state = ({
      html:'',
      modal: true,
      showBtn:false,
      lensList: this.props.navigation.getParam('lensList'),
      tempId: this.props.navigation.getParam('tempId'),
      userId: this.props.navigation.getParam('userId'),
      mp3: this.props.navigation.getParam('mp3'),
      single: this.props.navigation.getParam('single'),
			url: '',
			loading:false
    })
  }
  componentWillMount(){
		Orientation.lockToLandscape();
		
    //  
    let {lensList} = this.state;
    let time = 0;
    let first = lensList[0].during;
    lensList.forEach(item => {
      time = (time + parseFloat(item.during));
      item.time = (time - parseFloat(item.during))*1000;
    })
    // lensList.forEach(item => {
    //   item.time = item.time-first;
    // })
    console.log('lensList',lensList);
    this.setState({
      url: HTML_URL+this.state.lensList[0].lensId,
      lensList: lensList,
    })
    //this.getData(1);
  }
  componentDidMount(){
    //alert(this.state.mp3)
    if(this.state.mp3){
      this._play();
		}
		if(this.refs.tipModal){
			this.refs.tipModal._loading();
		}
		
  }
  componentWillUnmount() {
    count = 0;
    index = 0;
    this._stop();
    this.setState({
      showBtn:false,
    })
    //Orientation.lockToPortrait();
	}
	injectJS = () => {
		const script = 'document.write("Injected JS ")';  // eslint-disable-line quotes
		const js = 'document.getElementById("animation_container").style.width='+width+'"px"';
		if (this.webview) {
				this.webview.injectJavaScript(js);
		}
}
//document.getElementById("animation_container").style.width=width+"px";
//document.getElementById("animation_container").style.height=height+"px";
	setWH =()=>{
		return `alert(1)`
		
	}
  _play(){
    
    if(this.state.mp3=='null') return;
    try {
      SoundPlayer.playUrl(BASEURL+'music/playerMusic?fileName='+this.state.mp3);
    } catch (e) {
      console.log(`cannot play the sound file`, e)
    }
  }
  _stop(){
    SoundPlayer.stop();
  }
  _onLoadEnd(){
		this.refs.tipModal._close();
		// this.setState({
		// 	loading:false
		// })
    index ++;
    //this.refs.tipModal._success('1',500);
    // if(count !=0 ) return;
    // this._startTimer();
    // count = 1;
    let {lensList} = this.state;
    if(index < lensList.length){
      this._loadHtml(lensList[index].lensId,lensList[index].time);
    }

  }
  _startTimer(){
    let {lensList} = this.state;
    console.log('lensList',lensList);
    for(let i=1; i<lensList.length; i++){
      this._loadHtml(lensList[i].lensId, lensList[i].time);
    }
    // lensList.forEach((item,index) => {
    //   if(index != 0){
    //     this._loadHtml(item.lensId, item.time);
    //   }
    // })
  }
  _loadHtml(lensId,time){
    setTimeout(()=>{
      this.setState({
        url: HTML_URL+lensId,
      })
    },time);
  }
  //保存镜头
  _saveTemp(){
    let lensIds = [];
    this.state.lensList.forEach(item => {
      lensIds.push(item.lensId);
    })
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/saveTemp?tempId=' + this.state.tempId+'&lensIds='+lensIds+'&userId='+this.state.userId+'&mp3='+this.state.mp3)
    .then(res=>res.json())
    .then(response=>{
      this.refs.tipModal._close();
      if(response.succ == '1'){
        console.log('success')
        this.refs.tipModal._success('保存成功',1500)
        //this.refs.toast.show("保存成功");
      }
    })
    .catch(err=>{
      console.log('err')
      this.refs.tipModal._close();
    })
  }
  _toggle(){
    // if(this.state.single){
    //   return;
    // }
    this.setState({
      showBtn: !this.state.showBtn
    })
	}
	
  render(){
    return(
      <View style={{flex:1}}>
				<StatusBar hidden={true} backgroundColor='black' />
						{/* <Image style={{width:'100%',height:'100%'}} source={{uri:this.state.img}}/> */}
				{/* <WebView
					style={{flex:1}}
					source={{ uri: this.state.url }}
					onLoadEnd={()=> this._onLoadEnd()}
					javaScriptEnabled={true}
				/> */}
        {<WebView style={{flex:1,margin:0}}
					//ref="webView"
					ref={(webview) => this.webview = webview}
          //automaticallyAdjustContentInsets={true}
          //source={require('./A1_Canvas.html')}
          source={{uri:this.state.url}}
          javaScriptEnabled={true}
          scrollEnabled={false}
          domStorageEnabled={true}
          decelerationRate="normal"
          startInLoadingState={true}
          scalesPageToFit={true}
          allowUniversalAccessFromFileURLs={true }
          allowsInlineMediaPlayback={true}
					onLoadEnd={()=> this._onLoadEnd()}
					// injectedJavaScript={`
					// 	document.getElementById("animation_container").style.width=80px;
					// 	document.getElementById("animation_container").style.height=160px;
					// 	`}
					
				/>
				}
        <TipModal ref="tipModal"/>
        <Modal animationType='none' 
          transparent={true} 
          visible={this.state.modal} 
          onRequestClose={() => {this.setState({modal:false})}}
          style={styles.modal}
          >
          <TouchableOpacity style={styles.mView} activeOpacity={1.0} onPress={() => this._toggle()}>
          { !this.state.showBtn ? null :
            <View style={[styles.lView]}>
              <MyButton text='保存' press={()=>this._saveTemp()} 
                btnStyle={{marginLeft:0,marginRight:1,marginTop:0,
                paddingLeft:20,paddingRight:20,backgroundColor:'rgba(0,0,0,0.3)',
              marginBottom:1,borderRadius:5,}}/>
              <MyButton text='返回' press={()=>this.props.navigation.pop()} 
                btnStyle={{marginLeft:1,marginRight:1,marginTop:30,
                paddingLeft:20,paddingRight:20,backgroundColor:'rgba(0,0,0,0.3)',
              marginBottom:1,borderRadius:5,}}/>
            </View>
          }
          </TouchableOpacity>
        </Modal>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  lView:{
    backgroundColor:'rgba(0,0,0,0.0)',
    opacity:1,
    justifyContent:'center',
    alignItems:'center',
    marginRight:10,
  },
  mView:{
    flex:1,
    borderWidth:0,
    flexDirection:'row',
    //opacity:0.5,
    justifyContent:'flex-end',
    alignItems:'center',
    backgroundColor:'rgba(0, 0, 0, 0.0)',
  },
  modal:{
    flex:1,
  },
})